/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.volatileshooter.entity;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @author Ahmed
 */
public class EntityManager {

	private static EntityManager INSTANCE;
	private Map<String, Bucket> entities;

	public static EntityManager instance() {
		if (INSTANCE == null) {
			INSTANCE = new EntityManager();
		}

		return INSTANCE;
	}

	private EntityManager() {
		entities = new HashMap<String, Bucket>();
	}

	public Bucket addBucket(String bucketname, BucketManager controller) {
		Bucket bucket = new Bucket(bucketname, controller);
		entities.put(bucketname, bucket);
		return bucket;
	}

	public void removeBucket(String name) {
		entities.remove(name);
	}

	public Bucket getBucket(String name) {
		return entities.get(name);
	}

	public Set<String> getBucketKeys() {
		return entities.keySet();
	}

	public void fireEvent(EntityEvent event) {
		for (String key : entities.keySet()) {
			Bucket bucket = entities.get(key);
			for (int i = bucket.getEntities().size(); --i >= 0;) {
				Entity entity = bucket.getEntities().get(i);
				if (entity.getControllers() != null) {
					for (int j = entity.getControllers().size(); --j >= 0;) {
						entity.getControllers().get(j).event(event);
					}
				}
			}
		}
	}

	public void update(float time) {
		for (String key : entities.keySet()) {
			Bucket bucket = entities.get(key);
			bucket.update(time);
		}
	}
}
